import { forwardRef, useImperativeHandle, useState } from 'react'
import './index.scss'
import classNames from 'classnames'

type Props = {
  seconds?: number
  onEnd?: () => void
  style?: React.CSSProperties
  className?: string
}

export type CountDownExport = {
  /**
   * 开始倒计时
   * @returns
   */
  start: () => void
}

const CountDown = forwardRef<CountDownExport, Props>(
  ({ seconds = 60, onEnd, style, className }, ref) => {
    const [myseconds, setmySeconds] = useState(seconds)
    /**
     * 开始倒计时
     */
    function start() {
      const intervalId = setInterval(() => {
        // console.log('setInterval执行中')
        setmySeconds((pre) => {
          if (pre === 0) {
            // debugger
            // 倒计时结束
            // onEnd?.() 在此处不能调用父组件方法，警告：Warning: Cannot update a component from inside the function body of a different component
            onEnd?.()
            clearInterval(intervalId)
            return seconds// 重新恢复原值
          }
          return pre - 1
        })
      }, 1000)
    }

    // 暴露子组件内部的方法
    useImperativeHandle(ref, () => {
      return {
        start
      }
    })

    return (
      <div
        className={classNames('count-down-container', className)}
        style={style}
      >
        <span>{myseconds}s</span>
      </div>
    )
  }
)

export default CountDown
